package com.mydom4j.parse;

import com.mydom4j.util.DomGetter;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;

import java.io.File;
import java.util.Iterator;

/**
 * Created by wuxia on 2016/8/21 0021.
 */
public class Dom4JParser {
    public static void main(String[] args) {
        Document document = DomGetter.getDomFromFile(new File("C:/Users/wuxia/Desktop/spring.xml"));
        getSomeThing(document);
        parseSpring(document);
    }


    public static void getSomeThing(Document document) {
        System.out.println("docType = " + document.getDocType());
        System.out.println("XMLEncoding = " + document.getXMLEncoding());
        System.out.println("name = " + document.getName());
        System.out.println("path = " + document.getPath());
        System.out.println("xml = " + document.asXML());
    }

    public static void parseSpring(Document document) {
        Element root = document.getRootElement();
        System.out.println("name : " + root.getName());
        System.out.println("nameSpace = " + root.getNamespace().getStringValue());
        System.out.println("nameSpaceURI = " + root.getNamespaceURI());
        System.out.println("xsiNameSpace = " + root.getNamespaceForPrefix("xsi").getStringValue());
        Iterator iterator = root.attributeIterator();
        while (iterator.hasNext()) {
            Attribute attr = (Attribute)iterator.next();
            System.out.println("name= " + attr.getName() + " || value = " + attr.getValue());
        }

        System.out.println("===================================");

        elementIterator(root, null);
    }

    public static void elementIterator(Element element, String preStr) {
        if (null == preStr || "" == preStr) {
            preStr = "—";
        } else {
            preStr += "—";
        }

        Iterator elementIterator = element.elementIterator();
        while (elementIterator.hasNext()) {
            Element child = (Element)elementIterator.next();
            Iterator attributes = child.attributeIterator();
            System.out.println(preStr + "name = " + child.getName());
            int i = 0;
            while (attributes.hasNext()) {
                Attribute attr = (Attribute)attributes.next();
                System.out.print(preStr + "attr" + i + ":: attrName=" + attr.getName() + ", attrValue=" + attr.getValue() + "\n");
                i++;
            }
            System.out.print("\n");
            elementIterator(child, preStr);
        }
    }

}
